package com.alibaba.org.controller;

import com.alibaba.basic.query.BaseQuery;
import com.alibaba.basic.util.AjaxResult;
import com.alibaba.basic.util.PageList;
import com.alibaba.org.domain.Dept;
import com.alibaba.org.service.DeptService;
import com.alibaba.system.annotation.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Api(value = "部门的API",description="部门相关的CRUD功能")
@RestController
@RequestMapping("/dept")
public class DeptCollecter {
    @Autowired
    private DeptService deptService;

    // 查询所有
    @GetMapping
    public List<Dept> findAll() {
        return deptService.findAll();
    }
    // 单个查询
    @ApiOperation(value = "通过ID查询" )
    @GetMapping("/{id}")
    public Dept findById(@PathVariable("id")Long id) {
        return deptService.findById(id);
    }

    // 添加和修改,需要返回ajax结果
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Dept dept){
        try {
            if(dept.getId()==null){// 没有id就是新增，id自增，有id就是修改，id存在只需要修改别的内容
                deptService.add(dept);
            }else {
                deptService.update(dept);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }

    // 删除
    @ApiOperation(value = "删除接口")
    @DeleteMapping("/{id}")
    @PreAuthorize( name = "部门删除", sn = "dept:delete")
    public AjaxResult deleteDept(@PathVariable("id")Long id) {
        try {
        deptService.remove(id);
        return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }
    // 批量删除
    @PatchMapping
    public AjaxResult patchRemove(@RequestBody List<Long> ids) {
        try {
            deptService.patchRemove(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }
    // 高级查询
    @PostMapping
    public PageList<Dept> queryPage(@RequestBody BaseQuery baseQuery) {
       return deptService.query(baseQuery);
    }
    // 级联查询 返回为集合 因为都要查询，所以不需要传入查询内容
    @GetMapping("/depttree")
    public List<Dept> deptTreeQuery() {
        return deptService.deptTreeQuery();
    }
}
